<?php

namespace App\Http\Controllers\Admin\V1;

use App\Http\Controllers\Controller;
use App\Jobs\LoginLog;
use App\Models\User;
use Dingo\Api\Http\Response;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use League\Fractal\TransformerAbstract;

class LoginController extends Controller
{
    // 最大尝试登录次数
    protected $maxAttempts = 5;

    // 限制时间
    protected $timer = 60;

    /**
     * 登录
     * @param Request $request
     * @return JsonResponse|void
     */
    public function login(Request $request)
    {
        // 调用最大尝试登录
        if (!$this->maxAttempts()) {
            return $this->response->error('错误次数过多，请于一分钟后重试', 429);
        }

        $credentials = request(['username', 'password']);
        if (!$token = auth('api')->attempt($credentials)) {

            return $this->response->error('登录失败，请检查用户名或者密码', 422);
        }

        if (!auth()->user()->status) {
            return $this->response->error('登录失败，你的账户已被封禁', 400);
        };

        // 记录日志信息
        $login_info = [
            'user_id' => auth()->id(),
            'ip' => $request->ip(),
        ];

        // 执行队列
        LoginLog::dispatch($login_info);

        return $this->respondWithToken($token);
    }

    /**
     * 最大尝试次数
     *
     * @return bool
     */
    public function maxAttempts(): bool
    {
        // 键
        $key = request()->getClientIp() . ':' . request()->server->get('REMOTE_PORT');

        if (Redis::exists($key)) {
            // 自增1
            $numAttempts = Redis::incr($key);

            if ($numAttempts >= $this->maxAttempts) {
                return false;
            }
        } else {
            // 创建缓存
            Redis::setex($key, $this->timer, 0);
        }

        return true;
    }

    /**
     * 生成token
     * @param $token
     * @return JsonResponse
     */
    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => auth('api')->factory()->getTTL(),
        ]);
    }

    /**
     * 退出登录
     *
     * @return Response|JsonResponse
     */
    public function logout()
    {
        auth('api')->logout();

        return $this->response->noContent();
    }

    /**
     * 刷新token
     * Refresh a token.
     *
     * @return JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth('api')->refresh());
    }

    /**
     * 我的信息
     *
     * @return Response
     */
    public function me()
    {
        $user = $this->adminUser()->user();

        return $this->response->item($user, new class() extends TransformerAbstract {
            public function transform(User $user)
            {
                return [
                    'id' => $user->id,
                    'name' => $user->name,
                    'username' => $user->username,
                    'avatar' => $user->avatar,
                    'avatar_url' => ossUrl($user->avatar),
                ];
            }
        });
    }
}
